import configparser

from sqlalchemy import create_engine


class MySQLWriter:
    """针对表结构数据"""
    def __init__(self, config_file):
        # 创建 ConfigParser 对象
        config = configparser.ConfigParser()
        # 读取配置文件
        config.read(config_file)
        # 获取数据库连接配置信息
        block = 'Database_test'  # 开发环境
        host = config.get(block, 'host')
        port = config.get(block, 'port')
        username = config.get(block, 'username')
        password = config.get(block, 'password')
        database = config.get(block, 'database')

        # 创建 SQLAlchemy 引擎
        self.engine = create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset=utf8')

    def write_to_mysql(self, dataframe, table_name):
        with self.engine.connect() as connection:
            dataframe.to_sql(name=table_name, con=connection, if_exists='append', index=False)
